// formPackage/pages/article/addArticleTheme/addArticleTheme.js

import { queryArticleThemeList, createArticleTheme } from "../../../../service/article_service"
import debounce from "../../../../tools/debounce";

let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeStyle: "",
    currentTheme: "",//当前话题
    inputTheme: "",
    themeList: [

    ],
    themeIndex: 100,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.queryArticleThemeList();
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.themeStyle) {
      this.setData({
        themeStyle: app.globalData.themeStyle
      })
    }
  },

  //自定义话题绑定:
  cellInputChange(e) {
    this.setData({
      inputTheme: e.detail.value,
      currentTheme: e.detail.value
    })
    if (this.data.inputTheme) {
      this.setData({
        themeIndex: 100
      })
    }
  },
  themeItemSelect(e) {
    let index = e.currentTarget.dataset.index;
    let item = this.data.themeList[index];
    this.setData({
      currentTheme: item.title,
      themeIndex: index
    })
  },

  //确认选择
  sureAction() {
    if (!this.data.currentTheme) {
      wx.showToast({
        title: '输入或者选择一个话题',
        icon: "none"
      })
      return;
    }
    if (this.data.themeIndex > 50) {
      this.setData({
        currentTheme: "# " + this.data.currentTheme
      })
    }

    if (this.data.themeIndex > 50) {
      debounce(this.createArticleTheme)
    } else {
      app.globalData.selectTheme = this.data.currentTheme;
      wx.navigateBack({
        delta: 0,
      })
    }

  },
  //创建帖子话题
  createArticleTheme() {
    wx.showLoading();
    createArticleTheme(this.data.currentTheme).then(res => {
      wx.hideLoading();
      console.log("JJLog:帖子话题创建:" + JSON.stringify(res));
      if (res.code == 200) {
        app.globalData.selectTheme = this.data.currentTheme;
        wx.navigateBack({
          delta: 0,
        })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "创建失败",
        icon: "none"
      })
      console.error("JJLog:createArticleTheme", err);
    })
  },

  queryArticleThemeList() {
    wx.showLoading();
    queryArticleThemeList().then(res => {
      wx.hideLoading();
      console.log("JJLog:话题列表是:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          themeList: res.data
        })
      }
    }).catch(err => {
      wx.hideLoading();
      console.error("JJLog:queryArticleThemeList", err);
    })
  },




})